package org.zz.gmhelper;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {
    /**
     * 将字符串转换为MD5散列值
     *
     * @param input 需要加密的字符串
     * @return MD5散列后的字符串
     */
    public static String encryptToMD5(String input) {
        try {
            // 创建 MessageDigest 对象用于生成MD5散列
            MessageDigest md = MessageDigest.getInstance("MD5");

            // 执行消息摘要
            byte[] messageDigest = md.digest(input.getBytes(StandardCharsets.UTF_8));

            // 将 byte 数组转换为 hex 字符串
            BigInteger no = new BigInteger(1, messageDigest);
            StringBuilder hashText = new StringBuilder(no.toString(16));

            // 如果产生的散列值不足32位，则用0填充
            while (hashText.length() < 32) {
                hashText.insert(0, "0");
            }

            return hashText.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 algorithm not found", e);
        }
    }

    public static void main(String[] args) {
        String input = "example string";
        String md5Hash = encryptToMD5(input);
        System.out.println("MD5 hash of '" + input + "': " + md5Hash);
    }
}
